<template>
  <div>
    <Form
      :model="searchForm"
      label-position="right"
      :rules="rule"
      ref="searchForm"
      slot="adaption-bar"
      :label-width="120"
    >
      <!-- swagger接口地址 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item prop="url" :label="$t('Swagger地址')">
            <Input type="text" v-model="searchForm.url" :placeholder="$t('swagger接口地址')">
              <!-- <template #append>
              <span>.com</span>
            </template> -->
            </Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="20" class="code-row-bg">
        <Col span="12">
          <!-- 用户名 -->
          <Form-item prop="userName" :label="$t('module.userManage.userName')">
            <Input type="text" v-model="searchForm.userName" :placeholder="$t('module.userManage.userName')"></Input>
          </Form-item>
        </Col>
        <Col span="12">
          <!-- 密码 -->
          <Form-item prop="password" :label="$t('密码')">
            <Input type="password" v-model="searchForm.password" :placeholder="$t('密码')"></Input>
          </Form-item>
        </Col>
      </Row>

      <!-- 查询\重置按钮 -->
      <!-- <Form-item prop="button">
        <RPButton optType="search" @click="search" />
      </Form-item> -->
    </Form>
    <InnerPageTable ref="SwaggerTable" :config="tableConfig">
      <div slot="table-bar" class="my-search-bar">
        <RPButton optType="search" @click="onSearch" />
        <div class="group-search" v-show="groupId">
          <span>接口分组</span>
          <Select v-model="groupId" style="width: 300px" @on-change="onGroupChange">
            <Option v-for="item in swaggerApiGroupList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </div>
      </div>
    </InnerPageTable>
  </div>
</template>
  
<script>
import { swaggerColumns } from './columns.js'
import { apiGroup, getSwaggerList } from '@/api/apiManagement.js'

export default {
  props: {
    apiGroupInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    apiInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    tenantCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      searchForm: {
        url: '',
        userName: '',
        password: '',
        tenantCode: this.tenantCode
      },
      rule: {
        url: [{ required: true, message: this.$t('请输入Swagger地址'), trigger: 'blur' }],
        userName: [{ required: true, message: this.$t('请输入用户名'), trigger: 'blur' }],
        password: [{ required: true, message: this.$t('请输入密码'), trigger: 'blur' }]
      },
      tableDataByAll: {},
      swaggerApiGroupList: [],
      groupId: '',
      copyApplicationId: '',
      applicationList: [],
      actions: [
        {
          text: this.$t('common.save'),
          theme: 'primary',
          handle: this.onSave
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ]
    }
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: this.querySwaggerList,
        columnsFn: swaggerColumns.bind(this)
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.$emit('SetTitle', this.$t('从Swagger获取API'))
      this.$emit('SetPageWidth', 800)
      this.$emit('SetPageMinHeight', 300)
      this.$emit('SetPageActions', this.actions)
      this.getServiceAddress()
    },
    // 获取服务地址
    getServiceAddress() {
      apiGroup.getServiceAddress({ routeId: this.apiGroupInfo.routeId }).then(res => {
        const info = res.data
        if (info.url) {
          this.searchForm.url = `${info.url}/${info.path}/v2/api-docs`
        } else {
          // ${当前域名}/apis/${上下文}/v2/api-docs?group=${服务地址}
          this.searchForm.url = `${window.location.origin}/apis/${info.path}/v2/api-docs?group=${info.serviceId}`
        }
      })
    },
    onSearch() {
      this.$refs['searchForm'].validate(valid => {
        if (valid) {
          this.$refs['SwaggerTable'].load(this.searchForm)
        }
      })
    },
    reset() {
      this.$refs['searchForm'].resetFields()
      this.onSearch()
    },
    onGroupChange(val) {
      this.$refs['SwaggerTable'].clearSelected()
      if (this.tableDataByAll[val]) {
        this.$refs['SwaggerTable'].responseProcess({ records: this.tableDataByAll[val] })
      } else {
        this.$refs['SwaggerTable'].responseProcess([])
      }
    },
    querySwaggerList({ responseProcess, param }) {
      const paramobj = Object.assign({}, this.searchForm, {
        password: window.$Base64.encode(this.searchForm.userName + ':' + this.searchForm.password)
      })
      getSwaggerList(paramobj).then(data => {
        const swaggerInfo = data.data
        let swaggerApiGroupList = []
        for (const key in swaggerInfo) {
          if (Object.hasOwnProperty.call(swaggerInfo, key)) {
            swaggerApiGroupList.push(key)
          }
        }
        this.swaggerApiGroupList = swaggerApiGroupList
        this.groupId = swaggerApiGroupList[0]
        this.tableDataByAll = swaggerInfo
        swaggerInfo.records = swaggerInfo[swaggerApiGroupList[0]]
        responseProcess(swaggerInfo)
      })
    },
    onSave() {
      this.actions[0].loading = true
      let list = this.$refs['SwaggerTable'].getSelectioned() || []
      if (list.length < 1) {
        this.$message.error({
          content: this.$t('common.warning.selctAddElement'),
          duration: 3
        })
        return
      }
      const apiList = []
      list.forEach(element => {
        apiList.push({
          groupPath: this.apiGroupInfo.path,
          routeId: this.apiGroupInfo.routeId,
          tenantCode: element.tenantCode,
          apiPath: element.apiPath,
          apiDesc: element.apiDesc,
          appCode: element.appCode,
          requestMethod: element.requestMethod
        })
      });
      apiGroup
        .batchAddApi(apiList)
        .then(response => {
          this.$message.success({
            content: this.$t('common.addSuccess'),
            duration: 3
          })
          this.$emit('Close', true)
        })
        .catch(() => {
          this.actions[0].loading = false
        })
    }
  }
}
</script>
  
<style lang="less" scoped>
.my-search-bar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .group-search {
    display: flex;
    align-items: center;
    > span {
      margin-right: 10px;
    }
  }
}
</style>
  